package com.dehui.traders.widgets;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by hqq on 18.4.25.
 */

public class HomeReView extends RecyclerView{

    private int oldfirstItemPosition;
    private OnRecyclerViewChangeListener onRecyclerViewChangeListener;

    public HomeReView(Context context) {
        super(context,null);
    }

    public HomeReView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setOnRecyclerViewChangeListener(OnRecyclerViewChangeListener onRecyclerViewChangeListener){
        this.onRecyclerViewChangeListener = onRecyclerViewChangeListener;
    }

    private void init() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        this.setLayoutManager(layoutManager);
        SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(this);
        this.addOnScrollListener(new RecyclerView.OnScrollListener(){

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch(newState) {
                    case 0:
                        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                            LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                            int firstItemPosition = linearManager.findFirstVisibleItemPosition();
                            oldfirstItemPosition = firstItemPosition;
                            recyclerView.postDelayed(()->{
                                if (oldfirstItemPosition == firstItemPosition){
                                    if (onRecyclerViewChangeListener != null)
                                        onRecyclerViewChangeListener.visityPositionChange(firstItemPosition + 1);
                                }
                            },300);
                        break;
                }
            }
        });
    }

    public interface OnRecyclerViewChangeListener{
        void visityPositionChange(int position);
    }


}
